package by.grsu.gordienko.dao;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;



import by.grsu.gordienko.entity.ServiceItem;
import by.grsu.gordienko.table.ServiceItemTable;

import com.epam.grsulab.webapi.dao.AbstractDao;

public class ServiceItemDao extends AbstractDao<ServiceItemTable, ServiceItem> {

	public ServiceItemDao(String rootFolderPath) {
		super(rootFolderPath);
	}

	@Override
	public void saveNew(ServiceItem newService) {
		newService.setId(getNextId());
		final ServiceItemTable serviceItemTable = deserializeFromXml();
		serviceItemTable.getRows().add(newService);
		serializeToXml(serviceItemTable);

	}

	@Override
	public void update(ServiceItem entity) {
		final ServiceItemTable serviceItemTable = deserializeFromXml();
		for (ServiceItem b : serviceItemTable.getRows()) {
			if (b.getId().equals(entity.getId())) {
				b.setOrderType(entity.getOrderType());
				b.setOwnerId(entity.getOwnerId());
				b.setSreviceid(entity.getSreviceid());
			}
		}
		serializeToXml(serviceItemTable);
	}

	@Override
	public ServiceItem get(Serializable id) {
		final ServiceItemTable serviceItemTable = deserializeFromXml();
		for (ServiceItem b : serviceItemTable.getRows()) {
			if (b.getId().equals(id)) {
				return b;
			}
		}
		return null;
	}

	@Override
	public List<ServiceItem> getAll() {
		ServiceItemTable serviceItemTable = deserializeFromXml();
		return serviceItemTable.getRows();
	}

	@Override
	public void delete(Serializable id) {
		final ServiceItemTable serviceItemTable = deserializeFromXml();
		ServiceItem toBeDeletedService = null;
		for (ServiceItem b : serviceItemTable.getRows()) {
			if (b.getId().equals(id)) {
				toBeDeletedService = b;
			}
		}
		serviceItemTable.getRows().remove(toBeDeletedService);
		serializeToXml(serviceItemTable);
	}

	@Override
	protected Class<ServiceItemTable> getTableClass() {
		return ServiceItemTable.class;
	}

}